package com.qf.shiro;

import com.qf.bean.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;

import java.util.Scanner;

/**
 * projectName: 2103--RBAC
 *
 * @author: MaTianWei
 * time: 2021/7/10 10:43
 * description:认证
 */

public class AuthorizationDemo {
    public static void main(String[] args) {
        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");

        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        Scanner scanner = new Scanner(System.in);
        System.out.println("请您输入输入账号!");
        String account = scanner.nextLine();
        System.out.println("请您输入输入密码!");
        String password = scanner.nextLine();
        UsernamePasswordToken token = new UsernamePasswordToken(account, password);
        try{
        subject.login(token);
            System.out.println("认证成功");
        }catch (AuthenticationException e){
            System.out.println("认证失败");
            e.printStackTrace();
        }
        //认证通过得到user
        User user = (User) subject.getPrincipal();
        System.out.println("principal："+user);


        boolean authenticated = subject.isAuthenticated();
        System.out.println("authenticated："+authenticated);

        while(true){
            System.out.println("请输入要查询的角色名：");
            String role = scanner.nextLine();
            boolean b = subject.hasRole(role);
            System.out.println("b = "+b);
            System.out.println("_+_++_+_+_+_+_+_+_+_+_+_+_+__+_+_+_+_+_+_+_+_+__+_++_+_+__+_+_+_");
            System.out.println("请输入要检查的权限：");
            String permission = scanner.nextLine();
            boolean permitted = subject.isPermitted(permission);
            System.out.println("permitted="+permitted);
        }
        //subject.logout();
    }
}
